I've been dancing around with this, but can't figure out how to add a column or criteria. This groups by the first "column", but how to make it group also by the last column?
This is the answer:
let array = [[3, 'name', 'old'],[4, 'lastname','young'],[2, 'name', 'old'],[4, 'lastname','old']];
let result = Object.values(array.reduce((c, v) => {
if (c[v[1]]) c[v[1]][0] += v[0]; //Add the first element if already exist
else c[v[1]] = v; //Assign the value if does not exist
return c;
}, {}));
console.log(result);
Expected Result
result =
[
[5, 'name', 'old'],
[4, 'lastname','young'],
[4, 'lastname','old']
];
Thank you!
In your situation, as a simple modification, for example, how about using the values of columns "B" and "C" as a key of the object of reduce as follows?
let array = [[3, 'name', 'old'], [4, 'lastname', 'young'], [2, 'name', 'old'], [4, 'lastname', 'old']];
let result = Object.values(array.reduce((c, v) => {
const k = v[1] + v[2];
if (c[k]) c[k][0] += v[0];
else c[k] = v;
return c;
}, {}));
console.log(result);
When this script is run, the following result is obtained.
[
[ 5, 'name', 'old' ],
[ 4, 'lastname', 'young' ],
[ 4, 'lastname', 'old' ]
]
function teste() {
let array = [[3, 'name', 'old'], [4, 'lastname', 'young'], [2, 'name', 'old'], [4, 'lastname', 'old']];
let result = Object.values(array.reduce((c, v) => {
if (c[v[1]]) c[v[1]][0] += v[0]; else c[v[1]] = v;
if (c[v[2]]) c[v[1]][0] += v[0]; else c[v[2]] = v;
return c;
}, {}));
console.log(result);
}
Execution log
2:03:43 PM Notice Execution started
2:03:43 PM Info [ [ 7, 'name', 'old' ],
[ 7, 'name', 'old' ],
[ 12, 'lastname', 'young' ],
[ 12, 'lastname', 'young' ] ]
2:03:44 PM Notice Execution completed